
# -*- coding:utf-8 -*-
import logging
import requests
import json
import sys
import re
import logging


reload(sys)

# Standard module stuff
WORDS = ["SHEBEIHAO","DINGWEIQI","SHEBEI"]
SLUG = "etms"


def getDefault(profile):

    persona = 'DINGDANG'
    if 'robot_name' in profile:
        persona = profile['robot_name']

    robot_name_cn = u'叮当'
    if 'robot_name_cn' in profile:
        robot_name_cn=profile['robot_name_cn']

    keyargs={}
    keyargs["persona"]=persona;
    keyargs["robot_name_cn"]=robot_name_cn

    return keyargs

def handle(text, mic, profile, wxbot=None):
    logger = logging.getLogger(__name__)



    keysargs=getDefault(profile)
    keysargs["cmic"]=mic;
    keysargs["wxbot"]=wxbot

    itmS=itmsService(**keysargs)

    # /**匹配设备号**/
    pattern = re.compile(ur'(设备)([，]?)([0-9]*)')
    text_utf8 = text.decode('utf-8')
    if pattern.match(text_utf8):
        m = pattern.search(text_utf8)
        deviceID = m.group(3)
        logging.info(u"设备号: %s",deviceID)
        itmS.searchDeviceID(deviceID)




def isValid(text):
    return any(word in text for word in [u"设备号", u"定位器",u"设备"])


class itmsService(object):
    def __init__(self, persona, robot_name_cn, mic, wxbot=None):
        super(itmsService, self).__init__()
        self.person=persona
        self.robot_name_cn=robot_name_cn
        self.mic=mic
        self.wxbot=wxbot
        self.appUrl="http://114.215.43.181:8080/"
        self.logger = logging.getLogger(__name__)


    def fetch_deviceID(self,deviceId):
        path=self.appUrl+"device/gpsInfo/"+deviceId
        result = requests.get(path, timeout=3)
        self.logger.info("请求地址:%s", path)
        res = json.loads(result.text, encoding='utf-8')
        return res


    def searchDeviceID(self,deviceID):
        if not deviceID.strip():
            self.mic.say(u"设备号不正确",cache=True)
            return
        self.mic.say(u"正在查询,请稍等.",cache=True)
        deviceData=self.fetch_deviceID(deviceID)
        self.logger.info("收到数据:%s",deviceData)
        if not deviceData :
            self.mic.say(u"查询失败.", cache=True)
            return
        if "message" in deviceData:
            self.mic.say(u"服务出错.", cache=True)
            return


        self.logger.info(u"收到数据 %s",deviceData)
        if not deviceData:
            self.mic.say(u"没有查询到")
        sDeviceID=deviceData["deviceId"]
        sPow=deviceData["power"]
        if not  sPow:
            sPow="0"
        sAddress=deviceData["address"]
        if not sDeviceID or not sAddress:
            self.mic.say(u"没有查到设备的相关信息")
        text=u"设备号" +str(sDeviceID)+u"电量"+str(sPow)+u"位置"+str(sAddress)
        self.mic.say(text)











